/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.RegisterForm;

public class RegisterAction extends Action {

	private FormBeanFactory<RegisterForm> formFactory = FormBeanFactory
			.getInstance(RegisterForm.class);

	public RegisterAction() {
	}

	public String getName() {
		return "register.do";
	}

	public String perform(HttpServletRequest request) {
		HttpSession session = request.getSession();

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {

			User user = new User();

			RegisterForm form = formFactory.create(request);
			request.setAttribute("registerForm", form);

			if (!form.isPresent()) {
				return "welcome.jsp?doreg=1";
			}

			errors.addAll(form.getValidationErrors());
			Session dbSession = DBHelper.getSessionFactory().openSession();
			if (errors.size() == 0) {
				List list = dbSession.createCriteria(User.class)
						.add(Restrictions.eq("username", form.getUsername()))
						.list();
				if (list.size() != 0) {
					errors.add("UserName already exists");
				}
			}
			if (errors.size() > 0) {
				return "welcome.jsp?doreg=1";
			}
			user = new User(form.getUsername(), form.getPassword(),
					Integer.parseInt(form.getAge()), form.getFirstName(),
					form.getLastName(), form.getTimeZone(), form.getEmail(),
					Integer.parseInt(form.getWeight()), 0, false);

			dbSession.beginTransaction();
			dbSession.save(user);
			dbSession.getTransaction().commit();

			// Fetch the items again, since we modified the list
			request.setAttribute("user", user);
			session.setAttribute("user", user);

			return "redirectToHome.jsp";

		} catch (FormBeanException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
	}
}
